import { useMemo } from 'react';

import { FlowNodeInputTypeEnum } from '@/types/workflow/constant';
import { FlowNodeOutputItemType } from '@/types/workflow/io';

import { NodeCardProps } from '../render/NodeCard';
import { ReferenceLabel } from '../render/RenderInput/templates/Reference';
import Textarea from '../render/RenderInput/templates/Textarea';

function NodeVariableUpdateFolded(props: NodeCardProps) {
  const { inputs, nodeId } = props;
  const inputString = useMemo(() => JSON.stringify(inputs), [inputs]);
  const copyInputs = useMemo(() => {
    return JSON.parse(inputString) as FlowNodeOutputItemType[];
  }, [inputString]);

  return (
    <div className="ml-2 p-2 pb-4 text-gray-600">
      <div className="flex w-full gap-2">
        <span className="flex-shrink-0">回复</span>

        {copyInputs.map((item) => {
          return (
            <div key={item.id} className="flex w-full gap-2">
              {(() => {
                if (Array.isArray(item.value)) {
                  if (item.value && item.value.length > 1 && item.value[1]) {
                    return (
                      <ReferenceLabel
                        nodeId={nodeId}
                        variable={item.value as [string, string | undefined]}
                      />
                    );
                  }
                  return '未选择变量';
                }
                if (item.value === '') {
                  return '未赋值';
                }
                return (
                  <div key={item.key} className="pointer-events-none flex w-full gap-2">
                    {item.value ? (
                      <Textarea
                        item={{
                          ...item,
                          label: item.label ?? '', // 保证label为string类型，避免类型不兼容
                          renderTypeList: [FlowNodeInputTypeEnum.textarea], // 补充必需字段，实际可根据业务调整
                        }}
                        nodeId={nodeId}
                        isDisabled
                      />
                    ) : (
                      '未赋值'
                    )}
                  </div>
                );
              })()}
            </div>
          );
        })}
      </div>
    </div>
  );
}

export default NodeVariableUpdateFolded;
